// Copyright (c) 2011 Vratislav Cermak (vratacermak@gmail.com)
//  
// This file is part of SrtSync Project. See http://code.google.com/p/srtsync/ for more information.
//  
// SrtSync is an open source project. Using of SrtSync is free of charge.
// It is distributed under GNU General Public License version 3 (GPLv3).
// GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
//  
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the license for more details.

using System;
using System.Linq;
using System.Collections.Generic;
using SrtSync.Core;

namespace SrtSync.GtkWidgets
{
	public class EntriesNodesStore : Gtk.NodeStore
	{
		public EntriesNodesStore() : base(typeof(EntryNode))
		{
			//
		}
		
		public bool GetNodePosition(Entry entry, out int position)
		{            
			return GetNodePosition(GetNode(entry), out position);
		}
        
        public bool Empty
        {
            get 
            {
                foreach (EntryNode item in this)
                {
                    return false;
                }
                return true;
            }
        }
		
		public bool GetNodePosition(EntryNode node, out int position)
		{
			position = 0;
			foreach (EntryNode item in this)
			{
				if (item == node)
				{
					return true;
				}
				position++;
			}
			return false;
		}
		
		public void RemoveNode(Entry entry)
		{
			RemoveNode(GetNode(entry));
		}
		
		public EntryNode GetNode(Entry entry)
		{
			EntryNode result;
			if (GetNode(x => x.Entry == entry, out result))
			{
				return result;
			}
			return null;
		}
		
		public void RemoveNodes(IEnumerable<Entry> entries)
		{
			List<EntryNode> toRemove = new List<EntryNode>(this.Cast<EntryNode>().Where(y => entries.Contains(y.Entry)));
			foreach (EntryNode node in toRemove)
			{
				RemoveNode(node);
			}
		}
		
		private bool GetNode(Func<EntryNode, bool> func, out EntryNode node)
		{
		    node = this.Cast<EntryNode>().FirstOrDefault(func);
		    return node != null;
		}
	}
}